<script setup>
import {
  Delete,
    Document
} from '@element-plus/icons-vue'
import { ref } from 'vue'

//添加搜索数据模型
const recordsModel = ref({
  hostName: '',
  startTime: '',
  endTime: ''
})

const records = ref([
  {
    "id": "3",
    "ruleId": "0",
    "alertMessage": "内存使用过高",
    "severity": 11,
    "hostName": "1231231312",
    "hostIp": "1112-12312-12131",
    "occurrenceTime": "2024-5-5"
  }
])

//分页条数据模型
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(8)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  recordsList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  page.value = num
  recordsList()
}

// 这里应该绑定表单模型参数
//获取文章列表数据
import { alertRecordsListService, alertRecordDeleteService, recordTimeListService } from '@/api/records.js'


// 获取告警记录列表
const recordsList = async () => {
  // 将开始时间和结束时间转换为 ISO 8601 格式的字符串
  // 将开始时间和结束时间转换为后端所需的格式
  let startTime = recordsModel.value.startTime ? formatDate(recordsModel.value.startTime) : null;
  let endTime = recordsModel.value.endTime ? formatDate(recordsModel.value.endTime) : null;

  // 格式化日期时间为 "yyyy-MM-dd HH:mm:ss"
  function formatDate(dateTimeString) {
    const date = new Date(dateTimeString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  let params = {
    page: page.value,
    pageSize: pageSize.value,
    hostName: recordsModel.value.hostName || null,
    startTime: startTime,
    endTime: endTime
  };

  // console.log("开始时间:", startTime);
  // console.log("结束时间:", endTime);

  let result = await alertRecordsListService(params);
  //根据条件查询更新图标数据
  await recordTimeList(params);
  fetchData(); // 获取数据

  total.value = result.data.data.total;
  records.value = result.data.data.records;
};
recordsList();

//清空条件
// 重置表单的方法
const resetForm = () => {
  // 重置 recordsModel 中的属性为初始值
  recordsModel.value.hostName = '';
  recordsModel.value.startTime = '';
  recordsModel.value.endTime = '';
  recordsList();
};

import { ElMessage, ElMessageBox } from 'element-plus';
//删除弹窗
const deleteRecord = (row) => {
  ElMessageBox.confirm(
      '你确定删除该记录信息吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        // console.log(row.id);
        //调用接口
        let result = await alertRecordDeleteService(row.id);

        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        //调用获取全部记录函数——刷新页面
        recordsList();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
import * as echarts from "echarts";
import { onMounted } from "vue";
import request from "@/util/request.js";


const chartData = ref([
  {
    "time": "2024-5-5",
    "count": 0
  }
])

// 这里应该绑定表单模型参数
//根据时间查询条数
const recordTimeList = async (params) => {
  let result = await recordTimeListService(params);
  // console.log(result);

  // 清空 chartData 数组，以便重新填充数据
  chartData.value = [];

  // 检查 result.data.data 是否存在且是数组
  if (result.data && result.data.data && Array.isArray(result.data.data)) {
    // 遍历 result.data.data 数组，并将每个记录的时间和计数添加到 chartData 数组中
    result.data.data.forEach(record => {
      chartData.value.push({
        time: record.time,
        count: record.count
      });
    });

    // console.log(chartData.value);
  } else {
    console.warn("recordTimeList: 没有数据：'data' is not an array or is undefined");
  }
}

// 获取数据函数
const fetchData = async () => {
  init(chartData.value); // 将 chartData 传递给初始化函数
};

// 初始化图表
const init = (chartData) => {
  // 提取时间和计数数据
  const xAxisData = chartData.map(item => item.time); // 时间数据数组
  const seriesData = chartData.map(item => item.count); // 数值数据数组

  // 初始化echarts实例
  let myChart = echarts.init(document.getElementById("main"));
  // 绘制图表
  let option = {
    title: [
      {
        left: 'center',
        text: '告警情况'
      }
    ],
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      data: xAxisData // 使用时间数据数组
    },
    yAxis: {},
    series: [
      {
        type: 'line',
        showSymbol: false,
        data: seriesData // 使用数值数据数组
      }
    ]
  };
  // 渲染图表
  myChart.setOption(option);
};

//声明周期函数，自动执行初始化
onMounted(async () => {
  // 获取当前时间和开始时间（当前时间 - 10秒）
  const endTime = new Date();
  const startTime = new Date(endTime.getTime() - 10 * 1000);

  // const endTime = "2021-09-16 11:22:45";
  // const startTime = "2021-09-16 11:22:35";

  // 格式化时间为字符串（YYYY-MM-DD HH:MM:SS）
  const formatTime = (time) => {
    return time.toISOString().slice(0, 19).replace('T', ' ');
  };

  // 设置默认值
  let params = {
    startTime: recordsModel.value.startTime || formatTime(startTime),
    endTime: recordsModel.value.endTime || formatTime(endTime)
  };
  // // 设置默认值
  // let params = {
  //     startTime: recordsModel.value.startTime || (startTime),
  //     endTime: recordsModel.value.endTime || (endTime)
  // };
  // 获取数据并初始化图表
  await recordTimeList(params);
  fetchData(); // 获取数据
});

//--------------------------------------------
const isAlertDetailsVisible = ref(false) // 是否展示告警详情弹框
const alertData = ref()

const alertDetail = ref(
  {
    alertRuleDesc: '',
    allExpression: '',
    severity: 0,
    occurrenceTime: '',
    paramsMap: {}
  }
)

//告警详情
const getDetailRecord = (rowData) => {
  alertData.value = rowData;

  request.get(`/rules/details/${rowData.id}`).then(response => {
    alertDetail.value = response.data;
    isAlertDetailsVisible.value = true
    console.log(response.data);
  }).catch(error => {
    console.error(error);
  });
  console.log(alertDetail.value);
  console.log(alertDetail.value.alertRuleDesc);
}

const afterViewAlertDetails = () =>{
  isAlertDetailsVisible.value = false;
  alertDetail.value = null;
}

const getParamsMapData = (paramsMap) => {
  const data = [];
  for (const key in paramsMap) {
    const value = paramsMap[key];
    data.push({ key, value });
  }
  return data;
}

</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>告警异常记录</span>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form :model="recordsModel" inline>
            <el-form-item label="开始时间：">
                <el-date-picker v-model="recordsModel.startTime" type="datetime" placeholder="选择开始时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间：">
                <el-date-picker v-model="recordsModel.endTime" type="datetime" placeholder="选择结束时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="主机名：">
                <el-input v-model="recordsModel.hostName"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="recordsList">搜索</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
        <div style="width: 100%;height: 250px;" id="main">
        </div>
        <el-table :data="records" style="width: 100%" align-center>
            <el-table-column label="序号" width="100" type="index"> </el-table-column>
            <el-table-column label="告警信息" prop="alertMessage"></el-table-column>
            <el-table-column label="告警级别" prop="severity"></el-table-column>
            <el-table-column label="主机名" prop="hostName"></el-table-column>
            <el-table-column label="主机IP" prop="hostIp"></el-table-column>
            <el-table-column label="发生时间" prop="occurrenceTime"></el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button :icon="Document" plain type="primary" @click="getDetailRecord(row)"></el-button>
                  <el-button :icon="Delete" plain type="danger" @click="deleteRecord(row)"></el-button>
              </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
    </el-card>
    <el-dialog @close="afterViewAlertDetails" v-model="isAlertDetailsVisible" title="告警详情信息">
      <div>
        <p>告警规则描述: {{alertDetail.data.alertRuleDesc}}</p>
        <p>全部表达式: {{alertDetail.data.allExpression}}</p>
        <p>严重程度: {{alertDetail.data.severity}}</p>
        <p>发生时间: {{alertDetail.data.occurrenceTime}}</p>
      </div>
      <el-table :data="getParamsMapData(alertDetail.data.paramsMap)">
        <el-table-column prop="key" label="参数名"></el-table-column>
        <el-table-column prop="value" label="参数值"></el-table-column>
      </el-table>
    </el-dialog>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-table .cell {
        text-align: center !important;
    }

}
</style>